<template>
  <div class="residency-application">
    <h1>桂林电子科技大学科技园</h1>
    <h2>入 园 申 请 表 (迁入企业)</h2>

    <!-- 状态显示 -->
    <div v-if="form.status !== undefined" class="status-display">
      <el-tag
        :type="getStatusType(form.status)"
        size="large"
        effect="dark"
      >
        {{ getStatusText(form.status) }}
      </el-tag>
    </div>

    <el-form
      :model="form"
      ref="ruleFormRef"
      :rules="rules"
      label-width="150px"
      style="max-width: 1200px; width: 100%"
      :disabled="mode === 'view' || (form.status !== undefined && form.status === 1)"
    >
      <!-- 企业基本信息 -->
      <el-card>
        <div slot="header" class="header">企业基本信息</div>
        <el-form-item label="企业名称" prop="enterpriseName">
          <el-input v-model="form.enterpriseName" placeholder="请输入企业名称" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="法定人代表" prop="legalRepresentative">
              <el-input v-model="form.legalRepresentative" placeholder="请输入法定人代表" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="legalRepresentativePhone">
              <el-input
                v-model="form.legalRepresentativePhone"
                placeholder="请输入法定人联系电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱地址" prop="legalRepresentativeEmail">
              <el-input
                v-model="form.legalRepresentativeEmail"
                placeholder="请输入法定人邮箱地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="经办人" prop="handler">
              <el-input v-model="form.handler" placeholder="请输入经办人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="handlerPhone">
              <el-input v-model="form.handlerPhone" placeholder="请输入经办人联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱地址" prop="handlerEmail">
              <el-input v-model="form.handlerEmail" placeholder="请输入经办人邮箱地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="form.registeredAddress" placeholder="请输入注册地址" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="注册资本(万元)" prop="registeredCapital">
              <el-input v-model="form.registeredCapital" suffix="万元" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="员工人数" prop="employeeCount">
              <el-input v-model="form.employeeCount" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="初始入园人数" prop="initialParkEntryCount">
              <el-input v-model="form.initialParkEntryCount" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="成立日期" prop="establishmentDate">
              <el-date-picker
                v-model="form.establishmentDate"
                type="date"
                placeholder="请选择日期"
                value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="企业性质" prop="enterpriseNature">
          <el-select v-model="form.enterpriseNature" placeholder="请选择你的企业资质">
            <el-option label="大学生创业企业" value="大学生创业企业" />
            <el-option label="高校教师创业企业" value="高校教师创业企业" />
            <el-option label="民营企业" value="民营企业" />
            <el-option label="外资企业" value="外资企业" />
            <el-option label="股份制企业" value="股份制企业" />
            <el-option label="国有及国有控股企业" value="国有及国有控股企业" />
            <el-option label="其他企业" value="其他企业" />
          </el-select>
        </el-form-item>

        <!-- 新增企业资质部分 -->
        <el-form-item label="是否是高新技术企业" prop="highTech" @click="handleSpaceChange1(form.highTech)">
          <el-radio-group v-model="form.highTech">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="highTechCertification" v-if="form.highTech === 1">
          <el-input
            v-model="form.highTechCertification"
            placeholder="请输入证书编号"
          />
        </el-form-item>

        <el-form-item label="是否科技型中小企业" prop="techSmall" @click="handleSpaceChange2(form.techSmall)">
          <el-radio-group v-model="form.techSmall">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="techSmallCertification" v-if="form.techSmall === 1">
          <el-input
            v-model="form.techSmallCertification"
            placeholder="请输入证书编号"
          />
        </el-form-item>

        <el-form-item label="是否获得其他资质" prop="otherQualification" @click="handleSpaceChange3(form.otherQualification)">
          <el-radio-group v-model="form.otherQualification">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="otherQualificationName"  v-if="form.otherQualification === 1">
          <el-input
            v-model="form.otherQualificationName"
            placeholder="请输入资质名称"
          />
        </el-form-item>
        <el-form-item prop="otherQualificationCertification" v-if="form.otherQualification === 1">
          <el-input
            v-model="form.otherQualificationCertification"
            placeholder="请输入证书编号"
          />
        </el-form-item>

        <el-form-item label="企业类型" prop="enterpriseType">
          <el-select v-model="form.enterpriseType" placeholder="请选择你的企业类型">
            <el-option-group label="内资">
              <el-option label="国有" value="国有" />
              <el-option label="集体" value="集体" />
              <el-option label="股份合作" value="股份合作" />
              <el-option label="国有联营" value="国有联营" />
              <el-option label="集体联营" value="集体联营" />
              <el-option label="国有与集体联营" value="国有与集体联营" />
              <el-option label="其他联营" value="其他联营" />
              <el-option label="国有独资公司" value="国有独资公司"></el-option>
              <el-option label="其他有限责任公司" value="其他有限责任公司"></el-option>
              <el-option label="股份有限公司" value="股份有限公司"></el-option>
              <el-option label="私营独资" value="私营独资"></el-option>
              <el-option label="私营合伙" value="私营合伙"></el-option>
              <el-option label="私营有限责任公司" value="私营有限责任公司"></el-option>
              <el-option label="私营股份有限公司" value="私营股份有限公司"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-option-group>
            <el-option-group label="港澳台投资">
              <el-option label="港澳台商投资" value="港澳台商投资"></el-option>
              <el-option label="与港澳台商合资经营" value="与港澳台商合资经营"></el-option>
              <el-option label="与港澳台商合作经营" value="与港澳台商合作经营"></el-option>
              <el-option label="港澳台商独资" value="港澳台商独资"></el-option>
              <el-option label="港澳台商投资股份有限公司" value="港澳台商投资股份有限公司"></el-option>
              <el-option label="其他港澳台投资" value="其他港澳台投资"></el-option>
            </el-option-group>
            <el-option-group label="外商投资">
              <el-option label="外商投资" value="外商投资"></el-option>
              <el-option label="中外合资经营" value="中外合资经营"></el-option>
              <el-option label="中外合作经营" value="中外合作经营"></el-option>
              <el-option label="外资企业" value="外资企业"></el-option>
              <el-option label="外商投资股份有限公司" value="外商投资股份有限公司"></el-option>
              <el-option label="其他外商投资" value="其他外商投资"></el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="所属行业" prop="industry">
          <el-radio-group v-model="form.industry">
            <el-radio label="电子信息产业" value="电子信息产业">电子信息产业</el-radio>
            <el-radio label="生物医学产业" value="生物医学产业">生物医学产业</el-radio>
            <el-radio label="新能源产业" value="新能源产业">新能源产业</el-radio>
            <el-radio label="新材料产业" value="新材料产业">新材料产业</el-radio>
            <el-radio label="先进制造产业" value="先进制造产业">先进制造产业</el-radio>
            <el-radio label="环保节能减排" value="环保节能减排">环保节能减排</el-radio>
            <el-radio label="高技术服务业" value="高技术服务业">高技术服务业</el-radio>
            <el-radio label="软件外包服务业" value="软件外包服务业">软件外包服务业</el-radio>
            <el-radio label="其他" :value="otherIndustry">
              其他
              <el-input
                v-model="otherIndustry"
                placeholder="请填写其他行业"
                style="margin-left: 10px; width: 200px"
              />
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="主营业务" prop="mainBusiness">
          <el-input v-model="form.mainBusiness" placeholder="请填写主营业务" />
        </el-form-item>
        <el-form-item label="入园业务" prop="entryBusiness">
          <el-radio-group v-model="form.entryBusiness">
            <el-radio label="研究">研究</el-radio>
            <el-radio label="开发">开发</el-radio>
            <el-radio label="生产">生产</el-radio>
            <el-radio label="销售">销售</el-radio>
            <el-radio label="服务">服务</el-radio>
            <el-radio label="其他">其他</el-radio>
          </el-radio-group>
          <el-input
            v-if="form.entryBusiness === '其他'"
            v-model="form.otherBusinessType"
            placeholder="请填写其他业务"
            style="margin-left: 10px; width: 200px"
          />
        </el-form-item>
      </el-card>

      <!-- 园区场地租赁需求 -->
      <el-card>
        <div slot="header" class="header">园区场地租赁需求</div>
        <el-form-item label-width="0">
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="租赁面积" prop="rentalArea">
                <el-input type="text" v-model="form.rentalArea">
                  <template #suffix>平方米</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="租期" prop="leaseTerm">
                <el-input type="text" v-model="form.leaseTerm">
                  <template #suffix>年</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="位置要求" prop="locationRequirement">
          <el-input
            type="textarea"
            v-model="form.locationRequirement"
            placeholder="请输入位置要求"
          />
        </el-form-item>
        <el-form-item label="其他要求:">
          <el-input type="textarea" v-model="form.otherRequirements" placeholder="请输入其他要求" />
        </el-form-item>
      </el-card>

      <!-- 股东构成 -->
      <el-card>
        <div slot="header" class="header">股东构成</div>
        <el-form-item label-width="0" prop="shareholders">
          <el-table :data="form.shareholders" style="width: 100%">
            <el-table-column label="序号" type="index" width="60" />
            <el-table-column prop="name" label="股东姓名或名称">
              <template #default="scope">
                <el-form-item :prop="'shareholders.' + scope.$index + '.shareholderName'" :rules="[{ required: true, message: '请输入股东姓名', trigger: 'blur' }]">
                  <el-input v-model="scope.row.shareholderName" placeholder="股东名称"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="ratio" label="股份比例">
              <template #default="scope">
                <el-form-item :prop="'shareholders.' + scope.$index + '.shareRatio'" :rules="[{ required: true, message: '请输入股份比例', trigger: 'blur' }]">
                  <el-input v-model="scope.row.shareRatio" placeholder="股份比例"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="nature" label="股东性质">
              <template #default="scope">
                <el-form-item :prop="'shareholders.' + scope.$index + '.shareholderNature'" :rules="[{ required: true, message: '请输入股东性质', trigger: 'blur' }]">
                  <el-input v-model="scope.row.shareholderNature" placeholder="股东性质"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button type="danger" @click="removeShareholder(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="addShareholder">增加股东</el-button>
        </el-form-item>
      </el-card>

      <!-- 主要人员简介 -->
      <el-card>
        <div slot="header" class="header">主要人员简介</div>
        <el-form-item label-width="0" prop="keyPersonnel">
          <el-table :data="form.keyPersonnel" style="width: 100%">
            <el-table-column label="序号" type="index" width="60" />
            <el-table-column prop="name" label="姓名">
              <template #default="scope">
                <el-form-item :prop="'keyPersonnel.' + scope.$index + '.name'" :rules="[{ required: true, message: '请输入姓名', trigger: 'blur' }]">
                  <el-input v-model="scope.row.name" placeholder="人员姓名"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="birthDate" label="出生年月">
              <template #default="scope">
                <el-form-item :prop="'keyPersonnel.' + scope.$index + '.birthDate'" :rules="[{ required: true, message: '请选择出生年月', trigger: 'change' }]">
                  <el-date-picker
                    v-model="scope.row.birthDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="job" label="职务">
              <template #default="scope">
                <el-form-item :prop="'keyPersonnel.' + scope.$index + '.position'" :rules="[{ required: true, message: '请输入职务', trigger: 'blur' }]">
                  <el-input v-model="scope.row.position" placeholder="职务"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="school" label="毕业院校">
              <template #default="scope">
                <el-form-item :prop="'keyPersonnel.' + scope.$index + '.graduatedSchool'" :rules="[{ required: true, message: '请输入毕业院校', trigger: 'blur' }]">
                  <el-input v-model="scope.row.graduatedSchool" placeholder="毕业院校"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="职称">
              <template #default="scope">
                <el-form-item :prop="'keyPersonnel.' + scope.$index + '.title'" :rules="[{ required: true, message: '请输入职称', trigger: 'blur' }]">
                  <el-input v-model="scope.row.title" placeholder="职称"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="education" label="学历">
              <template #default="scope">
                <el-form-item :prop="'keyPersonnel.' + scope.$index + '.education'" :rules="[{ required: true, message: '请输入学历', trigger: 'blur' }]">
                  <el-input v-model="scope.row.education" placeholder="学历"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="major" label="专业">
              <template #default="scope">
                <el-form-item :prop="'keyPersonnel.' + scope.$index + '.major'" :rules="[{ required: true, message: '请输入专业', trigger: 'blur' }]">
                  <el-input v-model="scope.row.major" placeholder="专业"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button type="danger" @click="removeMember(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="addMember">增加成员</el-button>
        </el-form-item>
      </el-card>

      <!-- 入园项目简要介绍和分析 -->
      <el-card>
        <div slot="header" class="header">入园项目简要介绍和分析</div>

        <el-form-item label="项目简介" prop="projectIntroduction">
          <el-input
            v-model="form.projectIntroduction"
            type="textarea"
            placeholder="请输入项目的概述，包括目标、范围和主要特点等"
          />
        </el-form-item>
        <el-form-item label="竞争优势分析" prop="competitiveAdvantageAnalysis">
          <el-input
            v-model="form.competitiveAdvantageAnalysis"
            type="textarea"
            placeholder="请描述该项目相较于竞争对手的优势所在"
          />
        </el-form-item>
        <el-form-item label="市场前景分析" prop="marketProspectAnalysis">
          <el-input
            v-model="form.marketProspectAnalysis"
            type="textarea"
            placeholder="请分析该项目在当前市场环境下的发展潜力及预期增长趋势"
          />
        </el-form-item>
        <el-form-item label="能耗情况" prop="energyConsumption">
          <el-input
            v-model="form.energyConsumption"
            type="textarea"
            placeholder="请详细描述项目预计的能源消耗量及其对环境的影响"
          />
        </el-form-item>
        <el-form-item label="污染情况" prop="pollution">
          <el-input
            v-model="form.pollution"
            type="textarea"
            placeholder="请说明项目可能产生的污染物种类及其处理措施"
          />
        </el-form-item>
        <el-form-item label="噪声情况" prop="noise">
          <el-input
            v-model="form.noise"
            type="textarea"
            placeholder="请描述项目运行过程中可能产生的噪音水平及其控制方案"
          />
        </el-form-item>
        <el-form-item label="其他情况">
          <el-input
            v-model="form.otherProjectDetails"
            type="textarea"
            placeholder="请提供上述未涵盖但与项目相关的其他重要信息"
          />
        </el-form-item>
      </el-card>

      <!-- 知识产权情况 -->
      <el-card>
        <div slot="header" class="header">知识产权情况</div>
        <el-form-item label-width="0" prop="intellectualProperties">
          <el-table style="width: 100%" :data="form.intellectualProperties" v-if="form.intellectualProperties.length > 0">
            <el-table-column prop="name" label="名称">
              <template #default="scope">
                <el-form-item :prop="'intellectualProperties.' + scope.$index + '.name'"  >
<!--                              :rules="[{ required: true, message: '请输入名称', trigger: 'blur' }]"-->

                  <el-input v-model="scope.row.name" placeholder="请输入知识产权名称"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="类别">
              <template #default="scope">
                <el-form-item :prop="'intellectualProperties.' + scope.$index + '.type'" >
<!--                  :rules="[{ required: true, message: '请选择类别', trigger: 'change' }]"-->
                  <el-select v-model="scope.row.type" placeholder="请选择类别">
                    <el-option label="专利" value="patent"></el-option>
                    <el-option label="商标" value="trademark"></el-option>
                    <el-option label="著作权" value="copyright"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="applicationDate" label="申请时间">
              <template #default="scope">
                <el-form-item :prop="'intellectualProperties.' + scope.$index + '.applicationDate'" >
<!--                              :rules="[{ required: true, message: '请输入名称', trigger: 'blur' }]"-->

                  <el-date-picker
                    v-model="scope.row.applicationDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="approvalDate" label="批准时间">
              <template #default="scope">
                <el-form-item :prop="'intellectualProperties.' + scope.$index + '.approvalDate'" >
<!--                  :rules="[{ required: true, message: '请选择批准时间', trigger: 'change' }]-->
                  <el-date-picker
                    v-model="scope.row.approvalDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="danger" @click="removeIntellectualProperty(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="addIntellectualProperty">添加知识产权</el-button>
        </el-form-item>
      </el-card>

      <!-- 承担财政资金资助项目及获奖情况 -->
      <el-card>
        <div slot="header" class="header">承担财政资金资助项目及获奖情况</div>
        <el-form-item label-width="0" prop="fundingAndAwards">
          <el-table style="width: 100%" :data="form.fundingAndAwards"  v-if="form.fundingAndAwards.length > 0">
            <el-table-column prop="projectAwardName" label="项目奖项名称">
              <template #default="scope">
                <el-form-item :prop="'fundingAndAwards.' + scope.$index + '.projectAwardName'" :rules="[{ required: true, message: '请输入项目奖项名称', trigger: 'blur' }]">
                  <el-input v-model="scope.row.projectAwardName" placeholder="请输入项目奖项名称"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="level" label="级别">
              <template #default="scope">
                <el-form-item :prop="'fundingAndAwards.' + scope.$index + '.level'" :rules="[{ required: true, message: '请输入获奖级别', trigger: 'blur' }]">
                  <el-input v-model="scope.row.level" placeholder="请输入获奖级别"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="date" label="时间">
              <template #default="scope">
                <el-form-item :prop="'fundingAndAwards.' + scope.$index + '.date'" :rules="[{ required: true, message: '请选择时间', trigger: 'change' }]">
                  <el-date-picker
                    v-model="scope.row.date"
                    type="date"
                    placeholder="选择日期"
                    value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="governmentFundingAmount" label="获得政府资助金额">
              <template #default="scope">
                <el-form-item :prop="'fundingAndAwards.' + scope.$index + '.governmentFundingAmount'" :rules="[{ required: true, message: '请输入政府资助金额', trigger: 'blur' }]">
                  <el-input-number v-model="scope.row.governmentFundingAmount" :min="0"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="awardingDepartmentAndDate" label="颁奖部门/时间">
              <template #default="scope">
                <el-form-item :prop="'fundingAndAwards.' + scope.$index + '.awardingDepartmentAndDate'" :rules="[{ required: true, message: '请选择颁奖时间', trigger: 'change' }]">
                  <el-date-picker
                    v-model="scope.row.awardingDepartmentAndDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100px">
              <template #default="scope">
                <el-button type="danger" @click="removeFundingAndAward(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="addFundingAndAward">添加项目或奖项</el-button>
        </el-form-item>
      </el-card>

      <!-- 以往与桂电的合作情况 -->
      <el-card>
        <div slot="header" class="header">以往与桂电的合作情况</div>
        <el-form label-width="150px">
          <el-form-item label="合作描述" prop="previousCooperationWithGuet">
            <el-input type="textarea" v-model="form.previousCooperationWithGuet" placeholder="请输入合作描述"></el-input>
          </el-form-item>

          <!-- 可以根据需要添加更多的合作相关信息 -->
        </el-form>
      </el-card>
      <!-- 文件上传 -->
      <el-card>
        <div slot="header" class="header">上传文件</div>
        <el-form-item label="教师资格证" prop="teacherCertificate">
          <el-upload
            class="upload-demo"
            :http-request="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
            name="teacherCertificate"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="学生证" prop="studentCertificate">
          <el-upload
            class="upload-demo"
            :http-request="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
            name="studentCertificate"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="校友毕业证或学位证" prop="graduationCertificate">
          <el-upload
            class="upload-demo"
            :http-request="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
            name="graduationCertificate"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="form.highTech === 1" label="高新技术企业证书" prop="highTechCertification">
          <el-upload
            class="upload-demo"
            :http-request="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
            name="highTechCertification"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="form.techSmall === 1" label="科技型中小企业证书" prop="techSmallCertification">
          <el-upload
            class="upload-demo"
            :http-request="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
            name="techSmallCertification"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="form.otherQualification === 1" label="其他资质证书" prop="otherQualificationCertification">
          <el-upload
            class="upload-demo"
            :http-request="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
            name="otherQualificationCertification"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-card>

      <el-form-item label="科技园意见">
        <el-input disabled type="textarea" placeholder="等待领导填写意见" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注"/>
      </el-form-item>
      <el-form-item>
        <el-button v-if="mode !== 'view' && form.status !== 1" type="primary" @click="submitForm">提交</el-button>
        <el-button v-if="mode !== 'view' && form.status !== 1" @click="saveDraft">保存草稿</el-button>
        <el-button v-if="mode !== 'view' && form.status === 1" type="warning" @click="withdrawApplication">撤回申请</el-button>
        <el-button v-if="mode !== 'view' && form.status === 1" type="danger" @click="deleteApplication">删除申请</el-button>
        <el-button v-if="mode !== 'view'" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <span>注：请同时提供负责人身份证复印件。</span>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { newImmigrantApplication, getEnterpriseApplicationDetail, editImmigrantApplication, getMyImmigrantApplicationList, getImmigrantApplicationDetail, delImmigrantApplication } from '@/api/enterpeise';
import { uploadFile } from '@/api/file';
import type { ImmigrantApplication } from '@/types/ImmigrantApplication';
import type { ComponentSize, FormInstance, FormRules, UploadRequestOptions } from 'element-plus';
import type { AjaxResult } from '@/types/resultTypes';

const route = useRoute();
const router = useRouter();
const ruleFormRef = ref<FormInstance>();

// 获取模式（查看/编辑）
const mode = ref(route.query.mode as string || 'edit');

// 添加状态管理变量
const totalRecord = ref(0); // 用来标记用户是不是第一次提交 0，1表示是从我的申请中点击编辑过来的

// 扩展ImmigrantApplication类型，添加状态和ID字段
type ExtendedImmigrantApplication = Omit<ImmigrantApplication, 'entryBusiness'> & {
  status?: number; // 0-保存草稿，1-已提交，2-审核中，3-已完成
  id?: number; // ID字段用于编辑
  entryBusiness: string; // 单选字符串类型
  otherBusinessType?: string; // 其他业务类型
};

const handleSpaceChange1 = (val: string | number | boolean | undefined) => {
  if (val === 1) {
    form.value.highTechCertification = '';
  }
};
const handleSpaceChange2 = (val: string | number | boolean | undefined) => {
  if (val === 1) {
    form.value.techSmallCertification  = '';
  }
};
const handleSpaceChange3 = (val: string | number | boolean | undefined) => {
  if (val === 1) {
    form.value.otherQualificationName = '';
    form.value.otherQualificationCertification = '';
  }
};

// 表单验证规则
const rules = reactive<FormRules>({
  enterpriseName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  legalRepresentative: [{ required: true, message: '请输入法定代表人', trigger: 'blur' }],
  legalRepresentativePhone: [
    { required: true, message: '请输入法定代表人联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  legalRepresentativeEmail: [
    { required: true, message: '请输入法定代表人邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  handler: [{ required: true, message: '请输入经办人', trigger: 'blur' }],
  handlerPhone: [
    { required: true, message: '请输入经办人联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  handlerEmail: [
    { required: true, message: '请输入经办人邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  registeredAddress: [{ required: true, message: '请输入注册地址', trigger: 'blur' }],
  registeredCapital: [
    { required: true, message: '请输入注册资本', trigger: 'blur' },
    { pattern: /^([1-9]\d{0,9}|0)(\.\d{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' }],
  employeeCount: [
    { required: true, message: '请输入员工人数', trigger: 'blur' },
    { pattern: /^[1-9]\d{0,9}$/, message: '请输入正确的员工人数', trigger: 'blur' }
  ],
  initialParkEntryCount: [
    { required: true, message: '请输入初始入园人数', trigger: 'blur' },
    { pattern: /^[1-9]\d{0,9}$/, message: '请输入正确的初始入园人数', trigger: 'blur' }
  ],
  establishmentDate: [{ required: true, message: '请选择成立日期', trigger: 'change' }],
  enterpriseNature: [{ required: true, message: '请选择企业性质', trigger: 'change' }],
  enterpriseType: [{ required: true, message: '请选择企业类型', trigger: 'change' }],
  industry: [{ required: true, message: '请选择所属行业', trigger: 'change' }],
  mainBusiness: [{ required: true, message: '请输入主营业务', trigger: 'blur' }],
  entryBusiness: [{ required: true, message: '请选择入园业务', trigger: 'change' }],
  rentalArea: [
    { required: true, message: '请输入租赁面积', trigger: 'blur' },
    { pattern: /^([1-9]\d{0,9}|0)(\.\d{1,2})?$/, message: '请输入正确面积(两位小数)', trigger: 'blur' }
  ],
  leaseTerm: [
    { required: true, message: '请输入租期', trigger: 'blur' },
    { pattern: /^([1-9]\d{0,9}|0)(\.\d{1,2})?$/, message: '请输入正确租期(两位小数)', trigger: 'blur' }
  ],
  locationRequirement: [{ required: true, message: '请输入位置要求', trigger: 'blur' }],
  projectIntroduction: [{ required: true, message: '请输入项目简介', trigger: 'blur' }],
  competitiveAdvantageAnalysis: [{ required: true, message: '请输入竞争优势分析', trigger: 'blur' }],
  marketProspectAnalysis: [{ required: true, message: '请输入市场前景分析', trigger: 'blur' }],
  energyConsumption: [{ required: true, message: '请输入能耗情况', trigger: 'blur' }],
  pollution: [{ required: true, message: '请输入污染情况', trigger: 'blur' }],
  noise: [{ required: true, message: '请输入噪声情况', trigger: 'blur' }],
  shareholders: [{
    type: 'array',
    required: true,
    message: '请至少添加一个股东信息',
    trigger: 'change'
  }],
  keyPersonnel: [{
    type: 'array',
    required: true,
    message: '请至少添加一个主要人员信息',
    trigger: 'change'
  }],
  // 高新技术企业相关校验
  highTech: [{ required: true, message: '请选择是否是高新技术企业', trigger: 'change' }],
  highTechCertification: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (form.value.highTech === 1) {
          if (!value) {
            callback(new Error('请输入高新技术企业证书编号'));
          } else if (value.length > 50) {
            callback(new Error('证书编号长度不能超过50个字符'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  // 科技型中小企业相关校验
  techSmall: [{ required: true, message: '请选择是否是科技型中小企业', trigger: 'change' }],
  techSmallCertification: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (form.value.techSmall === 1) {
          if (!value) {
            callback(new Error('请输入科技型中小企业证书编号'));
          } else if (value.length > 50) {
            callback(new Error('证书编号长度不能超过50个字符'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  // 其他资质相关校验
  otherQualification: [{ required: true, message: '请选择是否获得其他资质', trigger: 'change' }],
  otherQualificationName: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (form.value.otherQualification === 1) {
          if (!value) {
            callback(new Error('请输入资质名称'));
          } else if (value.length > 100) {
            callback(new Error('资质名称长度不能超过100个字符'));
          } else if (!/^[\u4e00-\u9fa5A-Za-z0-9\s\-\(\)]+$/.test(value)) {
            callback(new Error('资质名称只能包含中文、英文、数字、空格、横线和括号'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  otherQualificationCertification: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (form.value.otherQualification === 1) {
          if (!value) {
            callback(new Error('请输入其他资质证书编号'));
          } else if (value.length > 50) {
            callback(new Error('证书编号长度不能超过50个字符'));
          } else if (!/^[A-Za-z0-9\-_]+$/.test(value)) {
            callback(new Error('证书编号只能包含字母、数字、横线和下划线'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]

});

const form = ref<ExtendedImmigrantApplication>(
  JSON.parse(
    // localStorage.getItem('ImmigrantApplicationForm') ||
      JSON.stringify({
        // 企业基本信息
        enterpriseName: '', // 企业名称：企业的正式注册名称
        legalRepresentative: '', // 法定代表人：企业的法定代表人的姓名
        legalRepresentativePhone: '', // 法定代表人电话：法定代表人的联系电话
        legalRepresentativeEmail: '', // 法定代表人邮箱：法定代表人的电子邮箱地址
        handler: '', // 联系人：负责与科技园沟通的主要联系人的姓名
        handlerPhone: '', // 联系人电话：主要联系人的联系电话
        handlerEmail: '', // 联系人邮箱：主要联系人的电子邮箱地址
        registeredAddress: '', // 注册地址：企业在工商部门注册的办公地址
        actualBusinessAddress: '', // 实际经营地址：企业实际运营的办公地点，可能与注册地址不同
        registeredCapital: 0.0, // 注册资本：企业在工商部门登记的注册资本金额
        paidInCapital: 0.0, // 实收资本：企业已经收到的投资金额
        lastYearRevenue: 0.0, // 上年营业收入：企业上一财年的总收入
        lastYearTa: 0.0, // 上年税收：企业上一财年缴纳的总税额
        employeeCount: 0, // 员工人数：企业当前的员工总数
        initialParkEntryCount: 0, // 初次入园人数：首次申请入驻科技园时的企业员工人数
        establishmentDate: null, // 成立日期：企业的成立日期

        // 企业性质和类型
        enterpriseNature: '', // 企业性质：例如国有企业、民营企业等（下拉框选择）
        enterpriseType: '', // 企业类型：例如生产型、服务型等（下拉框选择）
        industry: '', // 所属行业：企业所属的行业领域（下拉框选择）

        // 主营业务和入园信息
        mainBusiness: '', // 主营业务：企业的主要业务范围或产品描述
        entryMethod: '', // 入园方式：企业进入科技园的方式，如租赁、购买等（下拉框选择）
        entryBusiness: '', // 入园业务：企业计划在科技园内开展的具体业务（单选）
        otherBusinessType: '', // 其他业务类型
        rentalArea: 0.0, // 租赁面积：企业计划租赁的办公面积（平方米）
        leaseTerm: 0, // 租赁期限：企业计划租赁的时间长度（月/年）
        locationRequirement: '', // 地理位置要求：对办公地点的具体地理位置要求
        otherRequirements: '', // 其他要求：其他特殊要求或条件

        // 股东及关键人员信息
        shareholders: [
          // 股东信息列表
          {
            shareholderName: '', // 股东姓名：股东的姓名
            shareRatio: 0.0, // 持股比例：股东持有的股份比例
            shareholderNature: '', // 股东性质：例如自然人股东、法人股东等（下拉框选择）
          },
        ],
        keyPersonnel: [
          // 关键人员信息列表
          {
            name: '', // 姓名：关键人员的姓名
            birthDate: null, // 出生日期：关键人员的出生日期
            position: '', // 职位：关键人员在企业中的职位
            graduatedSchool: '', // 毕业院校：关键人员毕业的学校
            title: '', // 职称：关键人员的专业技术职称
            education: '', // 学历：关键人员的最高学历
            major: '', // 专业：关键人员所学的专业
          },
        ],

        // 项目与合作
        projectIntroduction: '', // 项目介绍：对企业项目的详细描述
        competitiveAdvantageAnalysis: '', // 竞争优势分析：企业相对于竞争对手的优势分析
        marketProspectAnalysis: '', // 市场前景分析：企业所在市场的未来发展趋势分析
        energyConsumption: '', // 能源消耗：企业预计的能源消耗情况
        pollution: '', // 环境污染：企业可能产生的环境污染情况
        noise: '', // 噪声：企业可能产生的噪声情况
        otherProjectDetails: '', // 其他项目详情：关于项目的其他重要信息

        // 知识产权情况
        intellectualProperties: [
          // 知识产权列表
          {
            name: '', // 名称：知识产权的名称
            type: '', // 类别：知识产权的类型，如专利、商标、著作权等（下拉框选择）
            applicationDate: null, // 申请时间：知识产权的申请日期
            approvalDate: null, // 批准时间：知识产权的批准日期
          },
        ],

        // 承担财政资金资助项目及获奖情况
        fundingAndAwards: [
          // 资助和获奖情况列表
          {
            projectAwardName: '', // 项目奖项名称：获得资助或奖励的项目名称
            level: '', // 级别：资助或奖励的级别，如国家级、省级等（下拉框选择）
            date: null, // 时间：获得资助或奖励的时间
            governmentFundingAmount: 0.0, // 获得政府资助金额：从政府获得的资金数额
            awardingDepartmentAndDate: '', // 颁奖部门/时间：颁发资助或奖励的政府部门及其时间
          },
        ],

        // 以往与桂电的合作情况
        previousCooperationWithGuet: '', // 以往合作情况：企业与桂林电子科技大学之前的合作经历描述

        // 园区意见和其他信息
        scienceParkOpinion: '', // 科技园区意见：科技园区对企业入驻申请的意见
        remarks: '', // 备注：其他需要说明的信息

        // 上传文件
        businessLicense: '', // 营业执照：企业的营业执照扫描件或复印件
        legalRepresentativeId: '', // 法定代表人身份证：法定代表人的身份证扫描件或复印件
        lastYearFinancialStatement: '', // 上年度财务报表：企业上一年度的财务报表
        proofOfIdentity: '', // 身份证明：用于验证身份的文件，如护照、身份证等
        teacherCertificate: '', // 新增
        studentCertificate: '', // 新增
        graduationCertificate: '', // 新增
        highTech: 0, // 新增
        highTechCertification: '', // 新增
        techSmall: 0, // 新增
        techSmallCertification: '', // 新增
        otherQualification: 0, // 新增
        otherQualificationName: '', // 新增
        otherQualificationCertification: '', // 新增

        // 状态管理
        status: 0, // 默认为草稿状态
        id: undefined,
      })
  )
);

//其他行业
const otherIndustry = ref('');

// 加载现有数据
const loadExistingData = async (id: any) => {
  try {
    // const bigIntId = BigInt(id);
    const res = await getImmigrantApplicationDetail(id) as unknown as AjaxResult<any>;

    if (res.code === 200) {
      // 处理时间字段格式转换
      const processedData = { ...res.data };

      // 处理成立日期
      if (processedData.establishmentDate) {
        processedData.establishmentDate = formatDateForDatePicker(processedData.establishmentDate);
      }

      // 处理入园业务字段 - 后端返回为数组，取第一个元素作为字符串
      if (Array.isArray(processedData.entryBusiness) && processedData.entryBusiness.length > 0) {
        processedData.entryBusiness = processedData.entryBusiness[0];
      } else if (typeof processedData.entryBusiness === 'string') {
        // 兼容后端直接返回字符串的情况
        processedData.entryBusiness = processedData.entryBusiness;
      } else {
        processedData.entryBusiness = '';
      }

      // 处理主要人员的时间字段
      if (processedData.keyPersonnel && Array.isArray(processedData.keyPersonnel)) {
        processedData.keyPersonnel = processedData.keyPersonnel.map((person: any) => ({
          ...person,
          birthDate: person.birthDate ? formatDateForDatePicker(person.birthDate) : null
        }));
      }

      // 处理知识产权的时间字段
      if (processedData.intellectualProperties && Array.isArray(processedData.intellectualProperties)) {
        processedData.intellectualProperties = processedData.intellectualProperties.map((property: any) => ({
          ...property,
          applicationDate: property.applicationDate ? formatDateForDatePicker(property.applicationDate) : null,
          approvalDate: property.approvalDate ? formatDateForDatePicker(property.approvalDate) : null
        }));
      }

      // 处理奖项的时间字段
      if (processedData.fundingAndAwards && Array.isArray(processedData.fundingAndAwards)) {
        processedData.fundingAndAwards = processedData.fundingAndAwards.map((award: any) => ({
          ...award,
          date: award.date ? formatDateForDatePicker(award.date) : null,
          awardingDepartmentAndDate: award.awardingDepartmentAndDate ? formatDateForDatePicker(award.awardingDepartmentAndDate) : null
        }));
      }

      // 处理其他行业字段
      if (processedData.industry && processedData.industry !== '其他') {
        otherIndustry.value = '';
      } else if (processedData.industry === '其他') {
        // 如果行业是"其他"，需要从其他字段获取具体行业名称
        // 这里可能需要根据实际数据结构调整
        // 暂时设置为空，用户需要重新输入
        otherIndustry.value = '';
      }

      // 填充表单数据
      Object.assign(form.value, processedData);
      totalRecord.value = 1; // 标记为编辑模式

      ElMessage.success('数据加载成功');
    } else {
      ElMessage.error(res.msg || '数据加载失败');
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error('数据加载失败');
  }
};

// 格式化日期为日期选择器需要的格式
const formatDateForDatePicker = (date: string | Date | null | undefined): string | null => {
  if (!date) return null;

  try {
    const dateObj = new Date(date);
    if (isNaN(dateObj.getTime())) return null;

    // 格式化为 YYYY-MM-DDTHH:mm:ss.SSSZ 格式
    const year = dateObj.getFullYear();
    const month = String(dateObj.getMonth() + 1).padStart(2, '0');
    const day = String(dateObj.getDate()).padStart(2, '0');
    const hours = String(dateObj.getHours()).padStart(2, '0');
    const minutes = String(dateObj.getMinutes()).padStart(2, '0');
    const seconds = String(dateObj.getSeconds()).padStart(2, '0');
    const milliseconds = String(dateObj.getMilliseconds()).padStart(3, '0');

    return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}Z`;
  } catch (error) {
    console.error('日期格式化失败:', error);
    return null;
  }
};

// 组件挂载时加载数据
onMounted(() => {
  // 从路由参数获取
  const id = route.query.id;
  console.log('sf', id);
  
  if (id) {
    loadExistingData(id.toString());
  }
});

// 增加股东
const addShareholder = () => {
  ruleFormRef.value?.clearValidate('shareholders');
  form.value.shareholders.push({
    shareholderName: '',
    shareRatio: 0.0,
    shareholderNature: '',
  });
};

// 删除股东
const removeShareholder = (index: number) => {
  form.value.shareholders.splice(index, 1);
};

//添加知识产权
const addIntellectualProperty = () => {
  
  form.value.intellectualProperties.push({
    name: '',
    type: '',
    applicationDate: '',
    approvalDate: '',
  });
};
//删除知识产权
const removeIntellectualProperty = (index: number) => {
  form.value.intellectualProperties.splice(index, 1);
};
//添加奖项
const addFundingAndAward = () => {
  form.value.fundingAndAwards.push({
    projectAwardName: '',
    level: '',
    date: '',
    governmentFundingAmount: 0,
    awardingDepartmentAndDate: '',
  });
};

//删除奖项
const removeFundingAndAward = (index: number) => {
  form.value.fundingAndAwards.splice(index, 1);
};

// 监听表单数据变化并保存到 localStorage
watch(
  form,
  (newForm) => {
    localStorage.setItem('ImmigrantApplicationForm', JSON.stringify(newForm));
  },
  { deep: true }
);

// 监听其他行业字段变化
watch(
  otherIndustry,
  (newValue) => {
    if (newValue) {
      form.value.industry = newValue;
    }
  }
);

// 增加成员
const addMember = () => {
  ruleFormRef.value?.clearValidate('keyPersonnel');
  form.value.keyPersonnel.push({
    name: '',
    birthDate: '',
    position: '',
    graduatedSchool: '',
    title: '',
    education: '',
    major: '',
  });
};

// 删除成员
const removeMember = (index: number) => {
  form.value.keyPersonnel.splice(index, 1);
};

// 上传相关方法
const handleSuccess = async (options: UploadRequestOptions) => {
  const formData = new FormData();
  formData.append('file', options.file);
  try {
    const result = await uploadFile(formData) as unknown as AjaxResult<any>;
    if (result.code === 200) {
      ElMessage.success('上传成功');
      // 根据上传的文件类型设置对应的字段
      const fileType = options.data?.name as string;
      if (fileType === 'teacherCertificate') {
        form.value.teacherCertificate = result.data;
      } else if (fileType === 'studentCertificate') {
        form.value.studentCertificate = result.data;
      } else if (fileType === 'graduationCertificate') {
        form.value.graduationCertificate = result.data;
      } else if (fileType === 'highTechCertification') {
        form.value.highTechCertification = result.data;
      } else if (fileType === 'techSmallCertification') {
        form.value.techSmallCertification = result.data;
      } else if (fileType === 'otherQualificationCertification') {
        form.value.otherQualificationCertification = result.data;
      }
    } else {
      ElMessage.error(result.msg || '上传失败');
    }
  } catch (error) {
    ElMessage.error('上传失败');
  }
};

const handleError = () => {
  ElMessage.error('上传失败');
};

const beforeUpload = (file: File) => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 2MB!');
  }
  return isLt2M;
};
// 格式化日期为 "yyyy-MM-dd HH:mm:ss"
const formatDateToServer = (dateString: any): string | null => {
  if (!dateString) return null;

  const date = new Date(dateString);
  if (isNaN(date.getTime())) return null;

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 提交表单
const submitForm = async () => {
  if (!ruleFormRef.value) return;

  await ruleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 设置状态为已提交
        form.value.status = 1;

        // 创建一个副本用于提交，并格式化日期字段
        const formData = JSON.parse(JSON.stringify(form.value));

        // 转换成立日期
        if (formData.establishmentDate) {
          formData.establishmentDate = formatDateToServer(formData.establishmentDate);
        }

        // 转换主要人员出生日期
        if (formData.keyPersonnel && Array.isArray(formData.keyPersonnel)) {
          formData.keyPersonnel = formData.keyPersonnel.map((p: any) => ({
            ...p,
            birthDate: formatDateToServer(p.birthDate)
          }));
        }

        // 转换知识产权申请/批准日期
        if (formData.intellectualProperties && Array.isArray(formData.intellectualProperties)) {
          formData.intellectualProperties = formData.intellectualProperties.map((ip: any) => ({
            ...ip,
            applicationDate: formatDateToServer(ip.applicationDate),
            approvalDate: formatDateToServer(ip.approvalDate)
          }));
        }

        // 转换奖项时间
        if (formData.fundingAndAwards && Array.isArray(formData.fundingAndAwards)) {
          formData.fundingAndAwards = formData.fundingAndAwards.map((fa: any) => ({
            ...fa,
            date: formatDateToServer(fa.date),
            awardingDepartmentAndDate: formatDateToServer(fa.awardingDepartmentAndDate)
          }));
        }

        // 使用 formData 提交数据
        const api = totalRecord.value === 1 ? editImmigrantApplication : newImmigrantApplication;
        const res = await api(formData) as unknown as AjaxResult<any>;

        console.log('API响应:', res);

        if (res.code === 200) {
          ElMessage.success(totalRecord.value === 1 ? '更新成功' : '提交成功');
          localStorage.removeItem('ImmigrantApplicationForm');
          router.push(`/personal-center/enterprise-settlement/my-application`);
        } else {
          ElMessage.error(res.msg || '提交失败');
        }
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败');
      }
    } else {
      ElMessage.warning('表单必填项未填写')
    }
  });
};


// 保存草稿
const saveDraft = async () => {
  try {
    // 设置状态为草稿
    form.value.status = 0;

    console.log('保存草稿的表单数据:', form.value);
    console.log('当前模式:', totalRecord.value === 1 ? '编辑' : '新建');

    // 创建一个副本用于提交，并格式化日期字段
    const formData = JSON.parse(JSON.stringify(form.value));

    // 转换成立日期
    if (formData.establishmentDate) {
      formData.establishmentDate = formatDateToServer(formData.establishmentDate);
    }

    // 转换主要人员出生日期
    if (formData.keyPersonnel && Array.isArray(formData.keyPersonnel)) {
      formData.keyPersonnel = formData.keyPersonnel.map((p: any) => ({
        ...p,
        birthDate: formatDateToServer(p.birthDate)
      }));
    }

    // 转换知识产权申请/批准日期
    if (formData.intellectualProperties && Array.isArray(formData.intellectualProperties)) {
      formData.intellectualProperties = formData.intellectualProperties.map((ip: any) => ({
        ...ip,
        applicationDate: formatDateToServer(ip.applicationDate),
        approvalDate: formatDateToServer(ip.approvalDate)
      }));
    }

    // 转换奖项时间
    if (formData.fundingAndAwards && Array.isArray(formData.fundingAndAwards)) {
      formData.fundingAndAwards = formData.fundingAndAwards.map((fa: any) => ({
        ...fa,
        date: formatDateToServer(fa.date),
        awardingDepartmentAndDate: formatDateToServer(fa.awardingDepartmentAndDate)
      }));
    }

    // 使用 formData 提交数据
    const api = totalRecord.value === 1 ? editImmigrantApplication : newImmigrantApplication;
    const res = await api(formData) as unknown as AjaxResult<any>;

    if (res.code === 200) {
      ElMessage.success('草稿保存成功');
      localStorage.removeItem('ImmigrantApplicationForm');
      router.push(`/personal-center/enterprise-settlement/my-application`);
    } else {
      ElMessage.error(res.msg || '保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败');
  }
};


// 重置表单
const resetForm = () => {
  ruleFormRef.value?.resetFields();
  form.value.otherRequirements = ''
  form.value.otherProjectDetails = ''
  form.value.previousCooperationWithGuet = ''
  form.value.remarks = ''
  localStorage.removeItem('ImmigrantApplicationForm');
};

// 撤回申请
const withdrawApplication = async () => {
  try {
    if (!form.value.id) {
      ElMessage.error('申请ID不存在');
      return;
    }

    // 设置状态为草稿
    form.value.status = 0;

    const res = await editImmigrantApplication(form.value) as unknown as AjaxResult<any>;
    if (res.code === 200) {
      ElMessage.success('撤回成功');
      router.push(`/personal-center/enterprise-settlement/my-application`);
    } else {
      ElMessage.error(res.msg || '撤回失败');
    }
  } catch (error) {
    console.error('撤回失败:', error);
    ElMessage.error('撤回失败');
  }
};

// 删除申请
const deleteApplication = async () => {
  try {
    if (!form.value.id) {
      ElMessage.error('申请ID不存在');
      return;
    }

    const res = await delImmigrantApplication(form.value.id.toString()) as unknown as AjaxResult<any>;
    if (res.code === 200) {
      ElMessage.success('删除成功');
      router.push(`/personal-center/enterprise-settlement/my-application`);
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败');
  }
};

// 获取状态类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0:
      return 'info'; // 草稿
    case 1:
      return 'warning'; // 已提交
    case 2:
      return 'primary'; // 审核中
    case 3:
      return 'success'; // 已完成
    default:
      return 'info';
  }
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '草稿';
    case 1:
      return '已提交';
    case 2:
      return '审核中';
    case 3:
      return '已完成';
    default:
      return '未知状态';
  }
};
</script>

<style lang="scss" scoped>
.header {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 20px;
}
.el-card {
  margin: 20px auto;
}
.residency-application {
  width: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-weight: bold;

  :deep(.el-form-item__label) {
    font-weight: bold;
  }

  :deep(.el-table th, .el-table td) {
    font-weight: bold;
  }
}

.status-display {
  margin: 20px 0;
  text-align: center;

  .el-tag {
    font-size: 16px;
    padding: 8px 16px;
  }
}
</style>

